<?php
/**
 * 登录控制器
 */

declare (strict_types = 1);

namespace app\controller\home;

use app\BaseController;
use app\model\admin\User;
use think\facade\Db;
use think\facade\Request;
use think\exception\ValidateException;
use think\facade\Validate;
use think\captcha\facade\Captcha;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Config;
use think\App;

class Login extends BaseController
{
    /**
     * 无需登录验证的方法
     */
    protected $noNeedLogin = ['index', 'login_submit', 'login_out'];

    /**
     * 分页参数
     */
    protected $defaultPage = 1;
    protected $defaultLimit = 15;
    protected $maxLimit = 100;

    /**
     * 构造函数
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    
    /**
     * 生成JWT
     * @param int $userId 用户ID
     * @return string
     */
    private function generateToken($userId)
    {
        $jwtConfig = Config::get('jwt');
        
        $payload = [
            'iss' => $jwtConfig['issuer'], // 签发者
            'aud' => $jwtConfig['audience'], // 接收方
            'iat' => time(), // 签发时间
            'exp' => time() + $jwtConfig['expire'], // 过期时间
            'sub' => $userId, // 主题（用户ID）
            'data' => ['userid' => $userId] // 兼容原系统的数据结构
        ];

        return JWT::encode($payload, $jwtConfig['key'], 'HS256');
    }

    /**
     * 登录页面
     */
    public function index()
    {
        return json(['code' => 0, 'msg' => 'success', 'data' => []]);
    }
    
    /**
     * 提交登录 - JWT认证方式
     */
    public function login_submit()
    {
        try {
            $data = Request::only(['username', 'password', 'captcha', 'captcha_token']);

            // 验证输入
            try {
                $validate = Validate::rule([
                    'username|用户名' => 'require',
                    'password|密码' => 'require',
                    'captcha|验证码' => 'require'
                ]);
                
                if (!$validate->check($data)) {
                    throw new ValidateException($validate->getError());
                }
                
                // 验证验证码
                $captchaValid = false;
                
                // 支持无状态验证码和原有session验证码
                if (isset($data['captcha_token'])) {
                    // 无状态验证码验证
                    $captchaValid = $this->verifyStatelessCaptcha($data['captcha'], $data['captcha_token']);
                } else {
                    // 默认使用原有session验证码
                    $captchaValid = Captcha::check($data['captcha']);
                }
                
                if (!$captchaValid) {
                    return json(['code' => 1, 'msg' => '验证码错误']);
                }
            } catch (ValidateException $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }

            // 查找用户
            $user = User::where('username', $data['username'])->find();

            if (!$user) {
                return json(['code' => 1, 'msg' => '用户不存在']);
            }
            
            // 检查用户状态
            if ($user->status != 1) {
                return json(['code' => 1, 'msg' => '用户已被禁用']);
            }

            // 验证密码 - 使用原有系统的方式
            if (md5(md5($data['password'] . $user->salt) . $user->salt) !== $user->pwd) {
                return json(['code' => 1, 'msg' => '用户名或密码错误']);
            }

            // 生成JWT
            $token = $this->generateToken($user->id);

            // 更新用户登录信息
            $updateData = [
                'last_login_time' => time(),
                'last_login_ip' => Request::ip(),
                'login_num' => $user->login_num + 1,
                'update_time' => time()
            ];
            
            Db::name('admin')->where(['id' => $user->id])->update($updateData);

            // 获取用户菜单权限
            $positionId = $user->getAttr('position_id') ?: 0;
            $groupIds = [];
            
            if ($positionId > 0) {
                $groupIds = Db::name('position_group')
                    ->where('pid', $positionId)
                    ->column('group_id');
            }
            
            $rules = [];
            if (!empty($groupIds)) {
                $rules = Db::name('admin_group')
                    ->where('id', 'in', $groupIds)
                    ->column('rules');
            }
            
            $ruleIds = [];
            if (!empty($rules)) {
                foreach ($rules as $rule) {
                    if (!empty($rule)) {
                        $ruleArray = explode(',', $rule);
                        $ruleIds = array_merge($ruleIds, $ruleArray);
                    }
                }
            }
            
            $ruleIds = array_unique($ruleIds);
            
            // 获取菜单列表
            $menuQuery = Db::name('admin_rule')
                ->where([
                    ['menu', '=', 1],
                    ['status', '=', 1]
                ]);
            
            // 检查是否为超级管理员（包含ID为1的规则）
            $isSuperAdmin = false;
            if (in_array('1', $ruleIds) || in_array(1, $ruleIds)) {
                $isSuperAdmin = true;
            }
            
            // 如果用户是超级管理员，则不进行权限过滤
            if ($isSuperAdmin) {
                // 直接获取所有菜单
                $menu = $menuQuery
                    ->order('sort asc, id asc')
                    ->select()
                    ->toArray();
            } else {
                // 普通用户按权限过滤
                if (!empty($ruleIds)) {
                    $menuQuery->where('id', 'in', $ruleIds);
                }
                
                $menu = $menuQuery
                    ->order('sort asc, id asc')
                    ->select()
                    ->toArray();
            }
            
            // 构建树形菜单结构
            $menuTree = $this->buildMenuTree($menu);
            
            // 获取部门信息
            $department = '';
            $did = $user->getAttr('did');
            if ($did > 0) {
                $deptInfo = Db::name('department')->where('id', $did)->value('title');
                $department = $deptInfo ?: '';
            }
            
            // 获取职位信息
            $position = '';
            $positionId = $user->getAttr('position_id');
            if ($positionId > 0) {
                $positionInfo = Db::name('position')->where('id', $positionId)->value('title');
                $position = $positionInfo ?: '';
            }

            // 返回用户信息和菜单权限
            // 处理头像路径：如果是本地路径，需要添加完整的URL前缀
            $avatar = $user->thumb ?: ($user->avatar ?? '');
            if ($avatar && !str_starts_with($avatar, 'http://') && !str_starts_with($avatar, 'https://')) {
                // 本地文件路径，添加API基础URL
                $avatar = request()->domain() . '/' . ltrim($avatar, '/');
            }
            
            $userInfo = [
                'id' => $user->id,
                'name' => $user->name,
                'username' => $user->username,
                'avatar' => $avatar,
                'thumb' => $avatar, // 保持兼容性
                'department' => $department,
                'position' => $position
            ];

            return json([
                'code' => 0,
                'msg' => '登录成功',
                'data' => [
                    'token' => $token,
                    'user_info' => $userInfo,
                    'menu' => $menuTree
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '登录失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 构建菜单树
     */
    private function buildMenuTree($menu, $parentId = 0)
    {
        $tree = [];
        if (!is_array($menu)) {
            return $tree;
        }
        
        foreach ($menu as $item) {
            if (isset($item['pid']) && $item['pid'] == $parentId) {
                $children = $this->buildMenuTree($menu, $item['id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
    
    /**
     * 退出登录
     */
    public function login_out()
    {
        try {
            // JWT是无状态的，服务端不需要特殊处理
            return json(['code' => 0, 'msg' => '退出成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '退出失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 锁屏
     */
    public function lock()
    {
        try {
            // 在JWT模式下，锁屏功能需要前端实现
            return json(['code' => 0, 'msg' => '锁屏功能已触发']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '操作失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 验证无状态验证码
     * @param string $code 用户输入的验证码
     * @param string $token 验证码token
     * @return bool
     */
    private function verifyStatelessCaptcha(string $code, string $token): bool
    {
        try {
            $key = Config::get('jwt.key', 'GOUGUOA');
            
            // 解码和解密
            $encrypted = base64_decode($token);
            $json = openssl_decrypt($encrypted, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
            
            if (!$json) {
                return false;
            }
            
            $data = json_decode($json, true);
            if (!$data || !isset($data['code']) || !isset($data['time'])) {
                return false;
            }
            
            // 检查是否过期（5分钟）
            if (time() - $data['time'] > 300) {
                return false;
            }
            
            // 验证码比较（不区分大小写）
            return strtoupper($code) === strtoupper($data['code']);
            
        } catch (\Exception $e) {
            return false;
        }
    }
    
}